package Demo;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class T1 {
    public static void main(String[] args) {
        List<Student> students = new ArrayList<>();
        Scanner scanner = new Scanner(System.in);

        System.out.println("请输入学生人数:");
        int numberOfStudents = scanner.nextInt();

        for (int i = 0; i < numberOfStudents; i++) {
            System.out.println("请输入第" + (i + 1) + "个人的信息: (id, name)");
            int id = scanner.nextInt();
            String name = scanner.next();
            Student student = new Student(id, name);  // 建立学生对象

            System.out.println("Enter number of scores for " + name + ":");
            int numberOfScores = scanner.nextInt();
            System.out.println("Enter scores:");

            for (int j = 0; j < numberOfScores; j++) {
                double score = scanner.nextDouble();
                student.addScore(score);  //
            }
            students.add(student);
        }

        writeStudentsToFile(students, "students.txt");

//        读取下来 打印在控制台上
        String path = "./students.txt";
        // 使用 try-with-resources 语句自动管理资源
        try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
            String line; // 在循环外声明 line 变量
            while ((line = reader.readLine()) != null) {
                System.out.println(line); // 在控制台打印每一行
            }
        } catch (IOException e) {
            e.printStackTrace(); // 处理可能的 IOException
        }

        scanner.close();  // 关闭scanner对象以释放资源
    }

    public static void writeStudentsToFile(List<Student> students, String filename) {
        try (BufferedWriter bw = new BufferedWriter(new FileWriter(filename,true))) {
            for (Student student : students) {
                bw.write(student.toString());
                bw.newLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
